const key = "Authorization";

function setToken(data) {
    document.cookie = key + "=" + escape(data.value) + ";expires="
        + new Date(data.expiresIn * 1000).toGMTString();
    localStorage.setItem("refreshToken", data.refreshToken);
    localStorage.setItem("tokenExpiresIn", data.expiresIn);
}

function refreshToken() {
    return new Promise((resolve, reject) => {
        let refreshToken = localStorage.getItem("refreshToken");
        $.get('/login/refreshAccessToken?refreshToken=' + refreshToken)
        .done(result => {
            if(result.code === 100) {
                setToken(result.data);
                resolve(result.data);
            } else {
                reject();
            }
        }).fail(e => {
            reject(e);
        });
    });
}

function isExpires() {
    let cookie = getCookie(key);
    let expiresIn = parseInt(localStorage.getItem("tokenExpiresIn"), 10);
    return new Date().getTime() > expiresIn * 1000 || !cookie;
}

function getCookie(name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if ((arr = document.cookie.match(reg))) {
        return unescape(arr[2]);
    }
    return null;
}

window.onload = function () {
    if(isExpires()) {
        let isLogin = window.location.pathname.startsWith("/login");
        refreshToken().then(() => {
            if (isLogin) {
                window.location.href = '/';
            }
        }).catch(() => {
            if (!isLogin) {
                window.location.href = '/login';
            }
        })
    }
}
